package com.fmatos.amazingwallpapers.view.detail;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.OnScaleGestureListener;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fmatos.amazingwallpapers.R;
import com.fmatos.amazingwallpapers.image.database.dto.ImageRow;
import com.fmatos.amazingwallpapers.imagemanagement.FileManager;
import com.fmatos.amazingwallpapers.imagemanagement.FileNotAvailableException;
import com.fmatos.amazingwallpapers.service.image.DownloadIntentService;

// TODO either eliminate pager or use it
public class ImageDetail extends Activity {

	private static final String TAG = ImageDetail.class.getSimpleName();
	
	public static final String INTENT_EXTRA_IMAGEROW = "INTENT_EXTRA_IMAGEROW";
	public static final String INTENT_EXTRA_ALBUM_ID = "INTENT_EXTRA_ALBUM_NAME";

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
	 * derivative, which will keep every loaded fragment in memory. If this
	 * becomes too memory intensive, it may be best to switch to a
	 * {@link android.support.v13.app.FragmentStatePagerAdapter}.
	 */
//	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
//	ViewPager mViewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_detail);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the activity.
//		mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

		// Set up the ViewPager with the sections adapter.
//		mViewPager = (ViewPager) findViewById(R.id.pager);
//		mViewPager.setAdapter(mSectionsPagerAdapter);
//		mViewPager.setCurrentItem(mSectionsPagerAdapter.getPosition());
	
	}
	
	@Override
	protected void onResume() {
	
		super.onResume();
//		Toast.makeText(this,"OnResume pager is running, position = " + mSectionsPagerAdapter.getPosition(), Toast.LENGTH_SHORT).show();
//		mViewPager.setCurrentItem(mSectionsPagerAdapter.getPosition()); 
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.image_detail, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	
	
	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 * TODO For larger sets of pages, consider FragmentStatePagerAdapter.
	 */
//	public class SectionsPagerAdapter extends FragmentPagerAdapter {
//		
//		private List<ImageRow> imageList;
//		private int position;
//		
//		public SectionsPagerAdapter(FragmentManager fm) {
//			super(fm);
//			loadImageList();			
//		}
//
//		@Override
//		public Fragment getItem(int position) {
//			// getItem is called to instantiate the fragment for the given page.
//			// Return a PlaceholderFragment (defined as a static inner class
//			// below).
//			Log.i(TAG,"get item = "  + position);
//			this.position = position;
//			// TODO carefull null pointer here
//			return PlaceholderFragment.newInstance(position + 1,imageList.get(position)); // replace position with imageRow
//		}
//
//		@Override
//		public int getCount() {
//			if ( imageList != null ) {
//				return imageList.size();
//			} else {
//				return 0;
//			}
//		}
//		
//		private void loadImageList() {
//			
//			ImagesDataSource mDatasource;
//			
//			// TODO protect from null pointerss
//			mDatasource = new ImagesDataSource(ImageDetail.this);
//			mDatasource.open(); // this may take a long time, so better run it in the background
//			
//			Bundle extras = getIntent().getExtras();
//			if (extras != null) {
//			    String value = extras.getString(INTENT_EXTRA_IMAGEROW);
//			    String albumName = extras.getString(INTENT_EXTRA_ALBUM_ID);
//			    
//			    imageList = mDatasource.getAlbumByName(albumName);
//			    Collections.reverse(imageList);
//			    position = -1;
//			    for ( ImageRow image : imageList ) {
//			    	position++;
//			    	if ( value.equals(image.getUrl())) { // TODO make code more efficient, use ID
//			    		break;
//			    	}
//			    }
//			}
//			
//			mDatasource.close(); 
//	
//		}
//
//		public int getPosition() {
//			return position;
//		}
//	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	@SuppressLint("ValidFragment")
	public static class PlaceholderFragment extends Fragment {

		private TextView txtCaption;
		private ImageView iView;
		private WebView webDescription;
		
		private FileManager fManager;
		private ImageRow image;
		
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private static final String ARG_SECTION_NUMBER = "section_number";

		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static PlaceholderFragment newInstance(int sectionNumber,ImageRow image) {
			PlaceholderFragment fragment = new PlaceholderFragment(image);
			Bundle args = new Bundle();
			Log.i(TAG,"New instance section = " + sectionNumber); // TODO read new image from here
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			fragment.setArguments(args);
				
			return fragment;
		}

		public PlaceholderFragment() {
			// need this code when rotating screen
		}
		
		@SuppressLint("ValidFragment")
		public PlaceholderFragment(ImageRow image) {
			super();
			this.image = image;
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_image_detail,
					container, false);

			txtCaption = (TextView) rootView
					.findViewById(R.id.txtDetailedCaption);
			
			webDescription = (WebView) rootView.findViewById(R.id.webDetailedDescription);
			
			iView = (ImageView) rootView.findViewById(R.id.imageDetailed);
			fManager = new FileManager(getActivity());

			drawImage(image);
			
			initZoomSupport();
			
			return rootView;
		}

		private void initZoomSupport() {


			// TODO try to reuse this code on the wallpaper screen
			OnScaleGestureListener listener = new OnScaleGestureListener() {
				
				private float scale = 1;
				private float displayedScale = 1;
				private static final float delta = 0.1f;
				
				@Override
				public void onScaleEnd(ScaleGestureDetector detector) {
					Log.v(TAG,"scale end at " + scale );
				}
				
				@Override
				public boolean onScaleBegin(ScaleGestureDetector detector) {
					Log.v(TAG,"scale begin at " + scale);
					return true;
				}
				
				@Override
				public boolean onScale(ScaleGestureDetector detector) {
					scale *= detector.getScaleFactor();

						iView.setScaleX(scale);
						iView.setScaleY(scale); // TODO set pivot point
						iView.invalidate();
						
						displayedScale = scale;
//					}
					
//					Log.v(TAG,"scale factor " + scale);
					return true;
				}
			};
			
			final ScaleGestureDetector scaleGestureDetector = new ScaleGestureDetector(getActivity(), listener);
			
			OnTouchListener touchListener = new OnTouchListener() {
				
				@SuppressLint("ClickableViewAccessibility")
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					return scaleGestureDetector.onTouchEvent(event);
				}
			};
			iView.setOnTouchListener(touchListener );
			
			
		}

		private void drawImage(final ImageRow image)  {
			
			if ( image  == null ) {
				return;
			} 
			if ( txtCaption != null ) {
				txtCaption.setText(image.getCaption());
			}
			
			if ( webDescription != null ) {
				if ( fManager.isImageGif(image.getFile()) ) {
					webDescription.loadUrl("file:///"  + image.getFile());
				} else {
					webDescription.getSettings().setLoadsImagesAutomatically(false);
					// TODO set text color to white, background to black
//					webDescription.loadData(image.getDescription(), "text/html", "utf-8");
					webDescription.loadData(image.getDescription(), "text/html; charset=UTF-8", null);
				}

			}
			getActivity().setTitle(image.getAlbum());
			
			
			if ( iView != null ) {
				try {
					iView.setImageBitmap(fManager.loadImageFromPath(image.getFile()));
//					WebView wv = (WebView) findViewById(R.id.webView1);
//					wv.loadUrl("file:///android_asset/anim5.gif");
					
				} catch (FileNotAvailableException e) {
					// TODO download image and try to draw again

					iView.setImageResource(R.drawable.ic_launcher);
					
					Log.e(TAG, e.toString());

					Handler handler = new Handler();
					ResultReceiver downloadResults = new ResultReceiver(handler ) {
						@Override
						protected void onReceiveResult(int resultCode,
								Bundle resultData) {
							
							String filename = resultData.getString(DownloadIntentService.BUNDLE_RESULT_FILENAME);
							if ( filename != null ) {
								try {
									iView.setImageBitmap(fManager.loadImageFromPath(filename));
									image.setFile(filename); // avoid image from being downloaded twice when swiping
									
									Log.i(TAG,"Download worked!!!");
								} catch (FileNotAvailableException e) {
									e.printStackTrace();
								}
							}
							super.onReceiveResult(resultCode, resultData);
						}
					};
					DownloadIntentService.downloadBitmap(getActivity(),image,downloadResults );
				}
			}
			
		}


	}

}
